package com.xls.rong;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;

import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;

import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.xls.rong.Utils.PreferenceUtil;
import com.xls.rong.entity.BaseEntity;
import com.xls.rong.entity.User;
import com.xls.rong.http.RetrofitHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.UserInfo;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";

    // UI references.
    @BindView(R.id.et_userId)
     AutoCompleteTextView mUserIdEdit;
    @BindView(R.id.et_userName)
     EditText mUserNameEdit;
    @BindView(R.id.login_progress)
     View mProgressView;
    @BindView(R.id.login_form)
     View mLoginFormView;
    @BindView(R.id.btn_login)
     Button loginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        User user = PreferenceUtil.getUser(this.getApplicationContext());
        if(user!=null && !TextUtils.isEmpty(user.getToken())){
            connect(user.getToken());
        }

        mUserNameEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {


        // Reset errors.
        mUserIdEdit.setError(null);
        mUserNameEdit.setError(null);

        // Store values at the time of the login attempt.
        final String userId = mUserIdEdit.getText().toString();
        final String userName = mUserNameEdit.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(userId)) {
            mUserIdEdit.setError(getString(R.string.error_invalid_password));
            focusView = mUserIdEdit;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(userName)) {
            mUserNameEdit.setError(getString(R.string.error_field_required));
            focusView = mUserNameEdit;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            User user = PreferenceUtil.getUser(this.getApplicationContext());
            if(user!=null && !TextUtils.isEmpty(user.getToken())){
                Log.d(TAG,"获取本地token成功:"+user.getToken());
                connect(user.getToken());
            }else{
                RetrofitHttp.getRetrofit().login(userId,userName)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<BaseEntity>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {

                            }

                            @Override
                            public void onNext(@NonNull BaseEntity baseEntity) {
                                Log.d(TAG,"请求成功:"+baseEntity.toString());
                                if(baseEntity.getCode()==200){
                                    final User user = new User();
                                    user.setUserId(baseEntity.getUserId());
                                    user.setUserName(userName);
                                    user.setToken(baseEntity.getToken());
                                    PreferenceUtil.saveUser(LoginActivity.this.getApplicationContext(),user);
                                    Log.d(TAG,"获取融云服务器token成功:"+user.getToken());
                                    connect(user.getToken());
                                    RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {
                                        @Override
                                        public UserInfo getUserInfo(String s) {
                                            UserInfo userInfo = new UserInfo(user.getUserId(),user.getUserName(),Uri.parse(user.getPortraitUri()));
                                            return userInfo;
                                        }
                                    },true);
                                }else{
                                    Toast.makeText(LoginActivity.this.getApplicationContext(),baseEntity.getCode()+"",Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }


        }
    }


    /**
     * 连接到融云
     * @param token
     */
    private void connect(String token) {
        showProgress(true);
        RongIM.connect(token, new RongIMClient.ConnectCallback() {

            /**
             * Token 错误。可以从下面两点检查 1.  Token 是否过期，如果过期您需要向 XlsApplication Server 重新请求一个新的 Token
             *                  2.  token 对应的 appKey 和工程里设置的 appKey 是否一致
             */
            @Override
            public void onTokenIncorrect() {
                showProgress(false);
                Log.e(TAG,"onTokenIncorrect ");
            }

            /**
             * 连接融云成功
             * @param userid 当前 token 对应的用户 id
             */
            @Override
            public void onSuccess(String userid) {
                showProgress(false);
                Log.d(TAG, "--onSuccess" + userid);
                stepToMain();

            }

            /**
             * 连接融云失败
             * @param errorCode 错误码，可到官网 查看错误码对应的注释
             */
            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                showProgress(false);
                Log.e(TAG,"onError  "+errorCode.getMessage());
            }
        });
    }



    private void stepToMain(){
        Map<String,Boolean> supportedConversation =  new HashMap<>();
        supportedConversation.put(Conversation.ConversationType.PRIVATE.getName(), false);
        RongIM.getInstance().startConversationList(this,supportedConversation);
        this.finish();
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }


}

